import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Card, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message,
  Descriptions,
  Radio
} from 'antd';
import { 
  UserOutlined, 
  EyeOutlined,
  CheckOutlined,
  CloseOutlined,
  PhoneOutlined,
  ShopOutlined,
  PlusOutlined
} from '@ant-design/icons';
import axios from 'axios';

const { Option } = Select;
const { TextArea } = Input;

const EmployerAudit = () => {
  const [loading, setLoading] = useState(false);
  const [employers, setEmployers] = useState([]);
  const [selectedEmployer, setSelectedEmployer] = useState(null);
  const [auditModalVisible, setAuditModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [addForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [filters, setFilters] = useState({
    status: ''
  });

  useEffect(() => {
    fetchEmployers();
  }, [pagination.current, pagination.pageSize, filters.status]);

  // 获取用工方列表
  const fetchEmployers = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('admin_token');
      console.log('获取用工方列表，参数:', {
        page: pagination.current - 1,
        size: pagination.pageSize,
        status: filters.status
      });
      
      const response = await axios.get('/api/admin/employers', {
        params: {
          page: pagination.current - 1,
          size: pagination.pageSize,
          status: filters.status
        },
        headers: { Authorization: `Bearer ${token}` }
      });

      console.log('用工方列表响应:', response.data);

      if (response.data.code === 200) {
        const pageData = response.data.data;
        console.log('分页数据:', pageData);
        console.log('用工方列表:', pageData.content);
        setEmployers(pageData.content || []);
        setPagination(prev => ({
          ...prev,
          total: pageData.totalElements || 0
        }));
        
        if (!pageData.content || pageData.content.length === 0) {
          console.log('没有找到用工方数据');
        }
      } else {
        console.error('获取用工方列表失败:', response.data.message);
        message.error(response.data.message || '获取数据失败');
      }
    } catch (error) {
      console.error('获取用工方列表失败:', error);
      console.error('错误详情:', error.response?.data);
      message.error('获取数据失败: ' + (error.response?.data?.message || error.message));
    } finally {
      setLoading(false);
    }
  };

  // 查看用工方详情
  const handleViewDetail = (employer) => {
    setSelectedEmployer(employer);
    setDetailModalVisible(true);
  };

  // 审核用工方
  const handleAudit = (employer) => {
    setSelectedEmployer(employer);
    form.setFieldsValue({
      status: '',
      remark: ''
    });
    setAuditModalVisible(true);
  };

  // 提交审核
  const handleSubmitAudit = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.put(`/api/admin/employers/${selectedEmployer.id}/audit`, {
        status: values.status,
        remark: values.remark
      }, {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.code === 200) {
        message.success('审核成功');
        setAuditModalVisible(false);
        form.resetFields();
        fetchEmployers();
      } else {
        message.error(response.data.message || '审核失败');
      }
    } catch (error) {
      console.error('审核失败:', error);
      message.error('审核失败');
    }
  };

  // 新增用工方
  const handleAddEmployer = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      console.log('创建用工方，数据:', values);
      
      const response = await axios.post('/api/admin/employers', values, {
        headers: { Authorization: `Bearer ${token}` }
      });

      console.log('创建用工方响应:', response.data);

      if (response.data.code === 200) {
        message.success('用工方创建成功');
        setAddModalVisible(false);
        addForm.resetFields();
        fetchEmployers();
      } else {
        console.error('创建用工方失败:', response.data.message);
        message.error(response.data.message || '创建失败');
      }
    } catch (error) {
      console.error('创建用工方失败:', error);
      console.error('错误详情:', error.response?.data);
      message.error('创建失败: ' + (error.response?.data?.message || error.message));
    }
  };

  // 处理筛选条件变化
  const handleFilterChange = (key, value) => {
    setFilters(prev => ({ ...prev, [key]: value }));
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理分页变化
  const handleTableChange = (paginationConfig) => {
    setPagination(prev => ({
      ...prev,
      current: paginationConfig.current,
      pageSize: paginationConfig.pageSize
    }));
  };

  // 获取状态标签
  const getStatusTag = (status) => {
    const statusMap = {
      PENDING: { color: 'orange', text: '待审核' },
      APPROVED: { color: 'green', text: '已通过' },
      REJECTED: { color: 'red', text: '已拒绝' }
    };
    const config = statusMap[status] || { color: 'default', text: '未知' };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 表格列定义
  const columns = [
    {
      title: '店主姓名',
      dataIndex: ['user', 'realName'],
      key: 'realName',
      render: (text, record) => (
        <Space>
          <UserOutlined />
          {text || record.user?.username || '未设置'}
        </Space>
      )
    },
    {
      title: '联系电话',
      dataIndex: ['user', 'phone'],
      key: 'phone',
      render: (text) => (
        <Space>
          <PhoneOutlined />
          {text || '未设置'}
        </Space>
      )
    },
    {
      title: '公司名称',
      dataIndex: 'companyName',
      key: 'companyName',
      render: (text) => (
        <Space>
          <ShopOutlined />
          {text || '未设置'}
        </Space>
      )
    },
    {
      title: '营业地址',
      dataIndex: 'businessAddress',
      key: 'businessAddress',
      ellipsis: true
    },
    {
      title: '审核状态',
      dataIndex: 'qualificationStatus',
      key: 'qualificationStatus',
      render: (status) => getStatusTag(status)
    },
    {
      title: '提交时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time) => time ? new Date(time).toLocaleString() : '-'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleViewDetail(record)}
          >
            查看详情
          </Button>
          {record.qualificationStatus === 'PENDING' && (
            <Button 
              type="link" 
              icon={<CheckOutlined />} 
              onClick={() => handleAudit(record)}
            >
              审核
            </Button>
          )}
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card title="用工方资质审核" extra={
        <Space>
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => setAddModalVisible(true)}
          >
            新增用工方
          </Button>
          <Select
            placeholder="审核状态"
            value={filters.status}
            onChange={(value) => handleFilterChange('status', value)}
            style={{ width: 120 }}
          >
            <Option value="">全部</Option>
            <Option value="PENDING">待审核</Option>
            <Option value="APPROVED">已通过</Option>
            <Option value="REJECTED">已拒绝</Option>
          </Select>
        </Space>
      }>
        <Table
          columns={columns}
          dataSource={employers}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
          onChange={handleTableChange}
        />
      </Card>

      {/* 详情模态框 */}
      <Modal
        title="用工方详细信息"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedEmployer && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="店主姓名" span={1}>
              {selectedEmployer.user?.realName || selectedEmployer.user?.username || '未设置'}
            </Descriptions.Item>
            <Descriptions.Item label="联系电话" span={1}>
              {selectedEmployer.user?.phone || '未设置'}
            </Descriptions.Item>
            <Descriptions.Item label="身份证号" span={1}>
              {selectedEmployer.user?.idCard || '未设置'}
            </Descriptions.Item>
            <Descriptions.Item label="地址" span={1}>
              {selectedEmployer.user?.address || '未设置'}
            </Descriptions.Item>
            <Descriptions.Item label="公司名称" span={2}>
              {selectedEmployer.companyName || '未设置'}
            </Descriptions.Item>
            <Descriptions.Item label="营业地址" span={2}>
              {selectedEmployer.businessAddress || '未设置'}
            </Descriptions.Item>
            <Descriptions.Item label="经营范围" span={2}>
              {selectedEmployer.businessScope || '未设置'}
            </Descriptions.Item>
            <Descriptions.Item label="法人代表" span={1}>
              {selectedEmployer.legalPerson || '未设置'}
            </Descriptions.Item>
            <Descriptions.Item label="联系电话" span={1}>
              {selectedEmployer.contactPhone || '未设置'}
            </Descriptions.Item>
            <Descriptions.Item label="审核状态" span={1}>
              {getStatusTag(selectedEmployer.qualificationStatus)}
            </Descriptions.Item>
            <Descriptions.Item label="提交时间" span={1}>
              {selectedEmployer.createdAt ? new Date(selectedEmployer.createdAt).toLocaleString() : '-'}
            </Descriptions.Item>
            {selectedEmployer.qualificationRemark && (
              <Descriptions.Item label="审核备注" span={2}>
                {selectedEmployer.qualificationRemark}
              </Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>

      {/* 审核模态框 */}
      <Modal
        title="审核用工方资质"
        open={auditModalVisible}
        onCancel={() => setAuditModalVisible(false)}
        onOk={() => form.submit()}
        okText="提交审核"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmitAudit}
        >
          <Form.Item
            label="审核结果"
            name="status"
            rules={[{ required: true, message: '请选择审核结果' }]}
          >
            <Radio.Group>
              <Radio value="APPROVED">通过</Radio>
              <Radio value="REJECTED">拒绝</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="审核备注"
            name="remark"
            rules={[{ required: true, message: '请输入审核备注' }]}
          >
            <TextArea rows={4} placeholder="请输入审核备注" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 新增用工方模态框 */}
      <Modal
        title="新增用工方"
        open={addModalVisible}
        onCancel={() => setAddModalVisible(false)}
        onOk={() => addForm.submit()}
        okText="创建"
        cancelText="取消"
        width={800}
      >
        <Form
          form={addForm}
          layout="vertical"
          onFinish={handleAddEmployer}
        >
          <div style={{ display: 'flex', gap: '16px' }}>
            <div style={{ flex: 1 }}>
              <h4>用户基本信息</h4>
              <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
              <Form.Item
                label="真实姓名"
                name="realName"
                rules={[{ required: true, message: '请输入真实姓名' }]}
              >
                <Input placeholder="请输入真实姓名" />
              </Form.Item>
              <Form.Item
                label="手机号码"
                name="phone"
                rules={[
                  { required: true, message: '请输入手机号码' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
                ]}
              >
                <Input placeholder="请输入手机号码" />
              </Form.Item>
              <Form.Item
                label="身份证号"
                name="idCard"
                rules={[
                  { required: true, message: '请输入身份证号' },
                  { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号' }
                ]}
              >
                <Input placeholder="请输入身份证号" />
              </Form.Item>
              <Form.Item
                label="地址"
                name="address"
              >
                <Input placeholder="请输入地址（可选）" />
              </Form.Item>
              <Form.Item
                label="初始密码"
                name="password"
                rules={[{ required: true, message: '请输入初始密码' }]}
              >
                <Input.Password placeholder="请输入初始密码" />
              </Form.Item>
            </div>
            <div style={{ flex: 1 }}>
              <h4>公司信息</h4>
              <Form.Item
                label="公司名称"
                name="companyName"
                rules={[{ required: true, message: '请输入公司名称' }]}
              >
                <Input placeholder="请输入公司名称" />
              </Form.Item>
              <Form.Item
                label="营业执照号"
                name="businessLicense"
              >
                <Input placeholder="请输入营业执照号（可选）" />
              </Form.Item>
              <Form.Item
                label="法人代表"
                name="legalPerson"
              >
                <Input placeholder="请输入法人代表（可选）" />
              </Form.Item>
              <Form.Item
                label="营业地址"
                name="businessAddress"
              >
                <Input placeholder="请输入营业地址（可选）" />
              </Form.Item>
              <Form.Item
                label="经营范围"
                name="businessScope"
              >
                <TextArea rows={3} placeholder="请输入经营范围（可选）" />
              </Form.Item>
              <Form.Item
                label="联系电话"
                name="contactPhone"
              >
                <Input placeholder="请输入联系电话（可选）" />
              </Form.Item>
            </div>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default EmployerAudit;
